package com.smart.service.impl;

import com.github.liaochong.myexcel.core.ExcelBuilder;
import com.github.liaochong.myexcel.core.FreemarkerExcelBuilder;
import com.github.liaochong.myexcel.core.WorkbookType;
import com.github.liaochong.myexcel.utils.AttachmentExportUtil;
import com.smart.common.enums.ErrorCode;
import com.smart.common.exception.BusinessException;
import com.smart.common.utils.AssertUtil;
import com.smart.context.SessionContext;
import com.smart.convert.SuperviseManageHotWorkExcelVOConvert;
import com.smart.helper.FileHelper;
import com.smart.helper.ReportHelper;
import com.smart.helper.TempHelper;
import com.smart.helper.WeeklyHelper;
import com.smart.mapper.HotWorkMapper;
import com.smart.mapper.JiansheProjectMapper;
import com.smart.mapper.ManageTempUserRegistrationMapper;
import com.smart.mapper.ManageUserRegistrationMapper;
import com.smart.mapper.ProjectMapper;
import com.smart.mapper.ProjectStatusAxisMapper;
import com.smart.mapper.QrCodeMapper;
import com.smart.mapper.UnitMapper;
import com.smart.model.convert.HotWorkConvert;
import com.smart.model.convert.ManageTempUserRegistrationConvert;
import com.smart.model.convert.ProjectConvert;
import com.smart.model.customdo.ProjectADO;
import com.smart.model.domain.HotWorkDO;
import com.smart.model.domain.ManageTempUserRegistrationDO;
import com.smart.model.domain.ManageUserRegistrationDO;
import com.smart.model.domain.ProjectDO;
import com.smart.model.domain.QrCodeDO;
import com.smart.model.domain.UnitDO;
import com.smart.model.excel.ServiceHotWorkExcelVO;
import com.smart.model.excel.ServiceTempUserExcelVO;
import com.smart.model.excel.ServiceUserExcelVO;
import com.smart.model.excel.SuperviseManageHotWorkExcelVO;
import com.smart.model.request.HotWorkRequest;
import com.smart.model.request.ManageTempUserRegistrationRequest;
import com.smart.model.request.ManageUserRegistrationRequest;
import com.smart.model.request.ProjectFileTaskRequest;
import com.smart.model.request.ProjectReportStatisticsRequest;
import com.smart.model.request.ProjectRequest;
import com.smart.model.request.ProjectWeeklyTaskRequest;
import com.smart.model.vo.DictItemVO;
import com.smart.model.vo.HotWorkVO;
import com.smart.model.vo.ManageTempUserRegistrationVO;
import com.smart.model.vo.ProjectReportExportVO;
import com.smart.model.vo.ProjectVO;
import com.smart.model.vo.StreetVO;
import com.smart.service.CreatExcelService;
import com.smart.service.DictItemService;
import com.smart.service.StreetService;
import com.smart.utils.ZipFileUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: zyh
 * @date: 2023-07-04
 */
@Slf4j
@Service
public class CreatExcelServiceImpl implements CreatExcelService {
    @Autowired
    private HotWorkMapper hotWorkMapper;
    @Autowired
    private ManageUserRegistrationMapper manageUserRegistrationMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private UnitMapper unitMapper;
    @Autowired
    private DictItemService dictItemService;
    @Autowired
    private StreetService streetService;
    @Autowired
    private ManageTempUserRegistrationMapper tempUserRegistrationMapper;
    @Autowired
    private QrCodeMapper codeMapper;
    @Autowired
    private JiansheProjectMapper jiansheProjectMapper;
    @Autowired
    private WeeklyHelper weeklyHelper;
    @Autowired
    private ReportHelper reportHelper;
    @Autowired
    private FileHelper fileHelper;
    @Autowired
    private TempHelper tempHelper;
    @Autowired
    private ProjectStatusAxisMapper axisMapper;

    /**
     * 云服务-动火作业导出
     *
     * @param request
     * @return
     */
    @Override
    public void serviceHotWorkExcelExport(HotWorkRequest request, HttpServletResponse response) {
        Long projectId = SessionContext.getProjectId();
        request.setProjectId(projectId);
        Map<String, Date> time = hotWorkMapper.selectTimeScop(request);
        List<HotWorkDO> list = hotWorkMapper.pageDetailedList(request);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(list), "未查询到数据");
        List<DictItemVO> dictItemVOS = dictItemService.queryDictItemByDictCode("HOT_WORK_TYPE");
        List<DictItemVO> hotWorkLv = dictItemService.queryDictItemByDictCode("HOT_WORK_LV");
        List<HotWorkVO> hotWorkVOList = HotWorkConvert.buildHotWorkVoList(list);
        fillInfo(hotWorkVOList);
        String timeScop = "";
        if (!ObjectUtils.isEmpty(hotWorkVOList)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
            Date hotWorkDateStart = request.getHotWorkDateStart();
            Date hotWorkDateEnd = request.getHotWorkDateEnd();
            if (!ObjectUtils.isEmpty(hotWorkDateStart) && !ObjectUtils.isEmpty(hotWorkDateEnd)) {
                timeScop = dateFormat.format(hotWorkDateStart) + "~" + dateFormat.format(hotWorkDateEnd);
            } else {
                if (!ObjectUtils.isEmpty(time)) {
                    timeScop = dateFormat.format(time.get("minTime")) + "~" + dateFormat.format(time.get("maxTime"));
                }
            }
        }
        List<ServiceHotWorkExcelVO> hotWorkExcelVOS = hotWorkVOList.stream().map(hotWorkVO -> {
            Date hotWorkDateStart = hotWorkVO.getHotWorkDateStart();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
            String format = null;
            if (!ObjectUtils.isEmpty(hotWorkDateStart)) {
                format = formatter.format(hotWorkDateStart);
            }
            DictItemVO itemVO = hotWorkLv.stream().filter(a -> a.getDictItemCode().equals(hotWorkVO.getHotWorkLv())).findFirst().orElse(new DictItemVO());
            String dictItemName = dictItemVOS.stream().filter(dictItemVO -> dictItemVO.getDictItemCode().equals(hotWorkVO.getHotWorkType())).findFirst().orElse(new DictItemVO()).getDictItemName();
            return ServiceHotWorkExcelVO.builder().hotWorkCode(hotWorkVO.getHotWorkCode()).hotWorkPosition(hotWorkVO.getHotWorkPosition()).hotWorkType(dictItemName).hotWorkDate(format).unitName(hotWorkVO.getUnitName()).hotWorkPersonName(hotWorkVO.getHotWorkPersonName()).hotWorkLookPersonOneName(hotWorkVO.getHotWorkLookPersonOneName()).hotWorkLookPersonTwoName(hotWorkVO.getHotWorkLookPersonTwoName()).safetyMeasure(hotWorkVO.getSafetyMeasure()).createTime(hotWorkVO.getCreateTime()).hotWorkLv(itemVO.getDictItemName()).build();
        }).collect(Collectors.toList());
        Map<String, Object> dataMap = new HashMap<>();
        List<ServiceHotWorkExcelVO> workExcelVOS = hotWorkExcelVOS.stream().sorted(Comparator.comparing(ServiceHotWorkExcelVO::getCreateTime).reversed()).collect(Collectors.toList());
        dataMap.put("hotWorkList", workExcelVOS);
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/serviceHotWorkExcelTemplet.ftl").build(dataMap);
            List<File> files = hotWorkVOList.stream().map(a -> {
                String hotWorkCode = a.getHotWorkCode();
                String name = hotWorkCode + ".png";
                try {
                    if (!ObjectUtils.isEmpty(a.getHotWorkCard()) && !"".equals(a.getHotWorkCard().trim())) {
                        File download = ZipFileUtils.download(name, a.getHotWorkCard());
                        return download;
                    }
                    return null;
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("云管理平台-动火证下载失败:{}", e.getMessage());
                    throw new BusinessException(ErrorCode.INTER_ERR, "云管理平台-动火证下载失败");
                }
            }).filter(a -> !ObjectUtils.isEmpty(a)).collect(Collectors.toList());
            String fileName = timeScop + "-动火作业导出";
            ZipFileUtils.downloadZip2(files, workbook, fileName, response);
        } catch (IOException e) {
            log.error("云服务-动火作业导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云服务-动火作业导出失败");
        }
    }

    /**
     * 云服务-工地人员台账导出
     *
     * @param request
     * @param response
     */
    @Override
    public void serviceUserExcelExport(ManageUserRegistrationRequest request, HttpServletResponse response) {
        if (ObjectUtils.isEmpty(request.getProjectId())) {
            request.setProjectId(SessionContext.getProjectId());
        }
        if ("ZONGBAO_UNIT".equals(request.getUnitProperty())) {
            request.setZbUnitType(request.getUnitProperty());
            request.setUnitProperty(null);
        }
        List<ManageUserRegistrationDO> registrationDOList = manageUserRegistrationMapper.pageQueryByRequest(request);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(registrationDOList), "未查询到数据");
        List<StreetVO> streetVOS = streetService.queryStreetByAreaCode("110115");
        List<DictItemVO> dictItemVOS = dictItemService.queryDictItemByDictCode("USER_JOB");
        List<DictItemVO> unitDicts = dictItemService.queryDictItemByDictCode("UNIT");
        List<DictItemVO> exitModes = dictItemService.queryDictItemByDictCode("OUT_TYPE");//离场方式
        List<ServiceUserExcelVO> userExcelVOS = registrationDOList.stream().map(user -> {
            ProjectDO projectDO = projectMapper.selectDOById(user.getProjectId());
            UnitDO unitDO = unitMapper.selectDOById(user.getUnitId());
            ServiceUserExcelVO userExcelVO = new ServiceUserExcelVO();
            if (!ObjectUtils.isEmpty(projectDO)) {
                Date entranceTime = user.getEntranceTime();
                Date exitTime = user.getExitTime();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
                String a = null;
                String b = null;
                if (!ObjectUtils.isEmpty(entranceTime)) {
                    a = simpleDateFormat.format(entranceTime);
                }
                if (!ObjectUtils.isEmpty(exitTime)) {
                    b = simpleDateFormat.format(exitTime);
                }
                String province = user.getProvince();
                String city = user.getCity();
                String area = user.getArea();
                String resideAddress = user.getExitResideAddress();
                if (StringUtils.isEmpty(province)) {
                    province = "";
                }
                if (StringUtils.isEmpty(city)) {
                    city = "";
                }
                if (StringUtils.isEmpty(area)) {
                    area = "";
                }
                if (StringUtils.isEmpty(resideAddress)) {
                    resideAddress = "";
                }
                String address = province + city + area + resideAddress;
                userExcelVO = ServiceUserExcelVO.builder().projectName(projectDO.getProjectName()).jianliUnit(projectDO.getJianliUnit()).shigongUnit(projectDO.getShigongUnit()).jiansheUnit(projectDO.getJiansheUnit()).shigongHeadName(projectDO.getShigongHeadName()).shigongHeadPhone(projectDO.getShigongHeadPhone()).street(streetVOS.stream().filter(streetVO -> streetVO.getCode().equals(projectDO.getStreetCode())).findFirst().orElse(new StreetVO()).getName()).userName(user.getUserName()).idCard(user.getIdCard()).jobType(dictItemVOS.stream().filter(dictItemVO -> dictItemVO.getDictItemCode().equals(user.getJobType())).findFirst().orElse(new DictItemVO()).getDictItemName()).userPhone(user.getUserPhone()).userAddress(user.getAddress()).inoculateNumber(!ObjectUtils.isEmpty(user.getInoculateNumber()) ? user.getInoculateNumber().toString() : null).entranceTime(a).commute(user.getCommute() == 0 ? "否" : "是").exitTime(b).exitMode(exitModes.stream().filter(dictItemVO -> dictItemVO.getDictItemCode().equals(user.getExitMode())).findFirst().orElse(new DictItemVO()).getDictItemName()).exitResideAddress(address).orderEntranceTime(user.getEntranceTime()).build();
                if (!ObjectUtils.isEmpty(unitDO)) {
                    String unitType = unitDicts.stream().filter(dictItemVO -> dictItemVO.getDictItemCode().equals(unitDO.getUnitType())).findFirst().orElse(new DictItemVO()).getDictItemName();
                    userExcelVO.setUnitType(unitType);
                    userExcelVO.setUnitName(unitDO.getUnitDetailName());
                } else {
                    Long projectId = user.getProjectId();
                    ProjectDO projectDOs = projectMapper.selectDOById(projectId);
                    userExcelVO.setUnitName(projectDOs.getShigongUnit());
                    userExcelVO.setUnitType("总包单位");
                }
            }
            return userExcelVO;
        }).sorted(Comparator.comparing(ServiceUserExcelVO::getOrderEntranceTime).reversed()).collect(Collectors.toList());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("userExcelVOS", userExcelVOS);
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/serviceUserExcelTemplet.ftl").build(dataMap);
            AttachmentExportUtil.export(workbook, "云服务平台-工地人员台账", response);
        } catch (IOException e) {
            log.error("云服务-大兴区建筑工地人员台账导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云服务-大兴区建筑工地人员台账导出失败");
        }
    }

    /**
     * 云服务-临时人员进出场纪录导出
     *
     * @param request
     * @param response
     */
    @Override
    public void serviceTempUserExcelExport(ManageTempUserRegistrationRequest request, HttpServletResponse response) {
        if (ObjectUtils.isEmpty(request.getProjectId())) {
            request.setProjectId(SessionContext.getProjectId());
        }
        List<ManageTempUserRegistrationDO> userRegistrationDOList = tempUserRegistrationMapper.selectByProject(request);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(userRegistrationDOList), "未查询到数据");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        List<ServiceTempUserExcelVO> tempUserExcelVOS = userRegistrationDOList.stream().map(tempUser -> {
            String province = tempUser.getProvince();
            String city = tempUser.getCity();
            String area = tempUser.getArea();
            String resideAddress = tempUser.getAddressDetails();
            if (StringUtils.isEmpty(province)) {
                province = "";
            }
            if (StringUtils.isEmpty(city)) {
                city = "";
            }
            if (StringUtils.isEmpty(area)) {
                area = "";
            }
            if (StringUtils.isEmpty(resideAddress)) {
                resideAddress = "";
            }
            String address = province + city + area + resideAddress;
            QrCodeDO qrCodeDO = codeMapper.selectDOById(tempUser.getEntranceAddress());
            QrCodeDO qrCodeDO1 = codeMapper.selectDOById(tempUser.getApproachAddress());
            ServiceTempUserExcelVO build = ServiceTempUserExcelVO.builder().entranceTime(!ObjectUtils.isEmpty(tempUser.getEntranceTime()) ? formatter.format(tempUser.getEntranceTime()) : null).entranceAddress(!ObjectUtils.isEmpty(tempUser.getEntranceAddress()) ? (!ObjectUtils.isEmpty(qrCodeDO) ? qrCodeDO.getAddress() : null) : null).userName(tempUser.getUserName()).userPhone(tempUser.getUserPhone()).idNumber(tempUser.getIdNumber()).addressDetails(address).receiver(tempUser.getReceiver()).approachAddress(!ObjectUtils.isEmpty(tempUser.getApproachAddress()) ? (!ObjectUtils.isEmpty(qrCodeDO1) ? qrCodeDO1.getAddress() : null) : null).approachTime(!ObjectUtils.isEmpty(tempUser.getApproachTime()) ? formatter.format(tempUser.getApproachTime()) : null).sortEntranceTime(tempUser.getEntranceTime()).build();
            return build;
        }).sorted(Comparator.comparing(ServiceTempUserExcelVO::getSortEntranceTime).reversed()).collect(Collectors.toList());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("tempUserExcelVOS", tempUserExcelVOS);
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/serviceTempUserExcelTemplet.ftl").build(dataMap);
            AttachmentExportUtil.export(workbook, "云服务平台-临时人员进出场纪录", response);
        } catch (IOException e) {
            log.error("云服务-临时人员进出场纪录导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云服务-临时人员进出场纪录导出失败");
        }
    }

    /**
     * 云管理-动火作业导出
     *
     * @param request
     * @param response
     */
    @Override
    public void manageHotWorkExcelExport(HotWorkRequest request, HttpServletResponse response) {
        List<DictItemVO> dictItemVOS = dictItemService.queryDictItemByDictCode("HOT_WORK_TYPE");
        Map<String, Date> time = hotWorkMapper.selectTimeScop(request);
        List<HotWorkDO> list = hotWorkMapper.pageDetailedList(request);
        List<DictItemVO> hotWorkLv = dictItemService.queryDictItemByDictCode("HOT_WORK_LV");
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(list), "未查询到数据");
        List<HotWorkVO> hotWorkVOList = HotWorkConvert.buildHotWorkVoList(list);
        fillInfo(hotWorkVOList);
        String timeScop = "";
        if (!ObjectUtils.isEmpty(hotWorkVOList)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
            Date hotWorkDateStart = request.getHotWorkDateStart();
            Date hotWorkDateEnd = request.getHotWorkDateEnd();
            if (!ObjectUtils.isEmpty(hotWorkDateStart) && !ObjectUtils.isEmpty(hotWorkDateEnd)) {
                timeScop = dateFormat.format(hotWorkDateStart) + "~" + dateFormat.format(hotWorkDateEnd);
            } else {
                if (!ObjectUtils.isEmpty(time)) {
                    timeScop = dateFormat.format(time.get("minTime")) + "~" + dateFormat.format(time.get("maxTime"));
                }
            }
        }
        List<ServiceHotWorkExcelVO> hotWorkExcelVOS = hotWorkVOList.stream().map(hotWorkVO -> {
            Date hotWorkDateStart = hotWorkVO.getHotWorkDateStart();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
            String format = null;
            if (!ObjectUtils.isEmpty(hotWorkDateStart)) {
                format = formatter.format(hotWorkDateStart);
            }
            DictItemVO itemVO = hotWorkLv.stream().filter(a -> a.getDictItemCode().equals(hotWorkVO.getHotWorkLv())).findFirst().orElse(new DictItemVO());
            String dictItemName = dictItemVOS.stream().filter(dictItemVO -> dictItemVO.getDictItemCode().equals(hotWorkVO.getHotWorkType())).findFirst().orElse(new DictItemVO()).getDictItemName();
            return ServiceHotWorkExcelVO.builder().hotWorkCode(hotWorkVO.getHotWorkCode()).hotWorkPosition(hotWorkVO.getHotWorkPosition()).hotWorkType(dictItemName).hotWorkDate(format).unitName(hotWorkVO.getUnitDetailName()).hotWorkPersonName(hotWorkVO.getHotWorkPersonName()).hotWorkLookPersonOneName(hotWorkVO.getHotWorkLookPersonOneName()).hotWorkLookPersonTwoName(hotWorkVO.getHotWorkLookPersonTwoName()).safetyMeasure(hotWorkVO.getSafetyMeasure()).projectNumber(hotWorkVO.getProjectNumber()).projectName(hotWorkVO.getProjectName()).createTime(hotWorkVO.getCreateTime()).hotWorkLv(itemVO.getDictItemName()).build();
        }).sorted(Comparator.comparing(ServiceHotWorkExcelVO::getCreateTime).reversed()).collect(Collectors.toList());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("hotWorkList", hotWorkExcelVOS);
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/manageHotWorkExcelTemplet.ftl").build(dataMap);
            List<File> files = hotWorkVOList.stream().map(a -> {
                String hotWorkCode = a.getHotWorkCode();
                String name = hotWorkCode + ".png";
                try {
                    if (!ObjectUtils.isEmpty(a.getHotWorkCard().trim())) {
                        File download = ZipFileUtils.download(name, a.getHotWorkCard());
                        return download;
                    }
                    return null;
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("云管理平台-动火证下载失败:{}", e.getMessage());
                    throw new BusinessException(ErrorCode.INTER_ERR, "云管理平台-动火证下载失败");
                }
            }).filter(a -> a != null).collect(Collectors.toList());
            HotWorkVO a = hotWorkVOList.get(0);
            String registrationNumber = a.getQualityRegistrationNumber();//质量监督注册号
            String projectName = a.getProjectName();
            String fileName = registrationNumber + "-" + projectName + "-" + timeScop + "-动火作业导出";
            ZipFileUtils.downloadZip2(files, workbook, fileName, response);
        } catch (IOException e) {
            log.error("云管理平台-动火作业导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云管理平台-动火作业导出失败");
        }
    }

    /**
     * 云监管-项目周报列表导出（项目周报台账）
     *
     * @param request
     * @param response
     */
    @Override
    public String projectWeeklyReportExcelExport(ProjectWeeklyTaskRequest request, HttpServletResponse response) {
        // 查询导出数据
        ProjectReportExportVO projectReportExportVO = reportHelper.queryWeeklyExportInfo(request);
        // 组装导出数据（处理需要导出压缩包的图片文件）
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("columnSpan", CollectionUtils.isNotEmpty(projectReportExportVO.getColumns()) ? projectReportExportVO.getColumns().size() + 11 : 11);
        dataMap.put("weeklyReportHead", projectReportExportVO.getColumns());
        dataMap.put("weeklyReportList", projectReportExportVO.getValues());
        dataMap.put("project", projectReportExportVO.getProjectDOS());
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = null;
            if (CollectionUtils.isNotEmpty(projectReportExportVO.getColumns()) && CollectionUtils.isNotEmpty(projectReportExportVO.getValues())) {
                workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/projectWeeklyReportExcelTemplat.ftl").build(dataMap);
                if (CollectionUtils.isEmpty(projectReportExportVO.getFiles())) {
                    log.info("只有文本填报项>>>>>>>>>>>>>>>>>>>>>>>>>>");
                    //AttachmentExportUtil.export(workbook, projectReportExportVO.getFileName(), response);
                    return ZipFileUtils.createAndUploadExcelFile(workbook, projectReportExportVO.getFileDirPath(), projectReportExportVO.getFileName());
                }
            }
            //zip文件名
            log.info("文本+图片填报项>>>>>>>>>>>>>>>>>>>>>>>>>>");
            return ZipFileUtils.createAndUploadZipFile(workbook, projectReportExportVO.getFileDirPath(), projectReportExportVO.getFileName());
        } catch (IOException e) {
            log.error("云监管平台-项目周报台账导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云监管平台-项目周报台账导出失败");
        }
    }

    @Override
    public void projectListWeeklyReportExcelExport(ProjectWeeklyTaskRequest request, HttpServletResponse response) {
        Pair<String, List<ProjectVO>> exportPair = weeklyHelper.queryExportInfo(request);
        AssertUtil.assertNotEmpty(exportPair.getRight(), "未查询到数据");
        List<SuperviseManageHotWorkExcelVO> excelVOBuilders = SuperviseManageHotWorkExcelVOConvert.convert(exportPair.getRight());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("excelVOBuilders", excelVOBuilders);
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/projectListWeeklyReportExcelTemplat.ftl").build(dataMap);
            AttachmentExportUtil.export(workbook, exportPair.getLeft(), response);
        } catch (IOException e) {
            log.error("云监管-项目名单导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云监管-项目名单导出失败");
        }
    }


    /**
     * 云管理平台-建筑工地人员台账导出
     *
     * @param request
     * @param response
     */
    @Override
    public void manageUserExcelExport(ManageUserRegistrationRequest request, HttpServletResponse response) {
        if ("ZONGBAO_UNIT".equals(request.getUnitProperty())) {
            request.setZbUnitType(request.getUnitProperty());
            request.setUnitProperty(null);
        }
        List<ManageUserRegistrationDO> manageUserRegistrationDOList = manageUserRegistrationMapper.pageQueryByRequest(request);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(manageUserRegistrationDOList), "未查询到数据");
        List<DictItemVO> dictItemVOS = dictItemService.queryDictItemByDictCode("USER_JOB");
        List<DictItemVO> unitDicts = dictItemService.queryDictItemByDictCode("UNIT");
        List<DictItemVO> exitModes = dictItemService.queryDictItemByDictCode("OUT_TYPE");//离场方式
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
        List<ServiceUserExcelVO> userExcelVOS = manageUserRegistrationDOList.stream().map(user -> {
            UnitDO unitDO = unitMapper.selectDOById(user.getUnitId());
            String idCard = user.getIdCard();
            String province = user.getProvince();
            String city = user.getCity();
            String area = user.getArea();
            String resideAddress = user.getExitResideAddress();
            if (StringUtils.isEmpty(province)) {
                province = "";
            }
            if (StringUtils.isEmpty(city)) {
                city = "";
            }
            if (StringUtils.isEmpty(area)) {
                area = "";
            }
            if (StringUtils.isEmpty(resideAddress)) {
                resideAddress = "";
            }
            String address = province + city + area + resideAddress;
            ServiceUserExcelVO userExcelVO = ServiceUserExcelVO.builder().userName(user.getUserName()).userPhone(user.getUserPhone()).idCard(idCard).jobType(dictItemVOS.stream().filter(dictItemVO -> dictItemVO.getDictItemCode().equals(user.getJobType())).findFirst().orElse(new DictItemVO()).getDictItemName()).userAddress(user.getAddress()).inoculateNumber(!ObjectUtils.isEmpty(user.getInoculateNumber()) ? user.getInoculateNumber().toString() : null).entranceTime(!ObjectUtils.isEmpty(user.getEntranceTime()) ? formatter.format(user.getEntranceTime()) : null).commute(user.getCommute() == 0 ? "否" : "是").exitTime(!ObjectUtils.isEmpty(user.getExitTime()) ? formatter.format(user.getExitTime()) : null).exitMode(exitModes.stream().filter(dictItemVO -> dictItemVO.getDictItemCode().equals(user.getExitMode())).findFirst().orElse(new DictItemVO()).getDictItemName()).exitResideAddress(address).orderEntranceTime(user.getEntranceTime()).build();
            if (!ObjectUtils.isEmpty(unitDO)) {
                String unitType = unitDicts.stream().filter(dictItemVO -> dictItemVO.getDictItemCode().equals(unitDO.getUnitType())).findFirst().orElse(new DictItemVO()).getDictItemName();
                userExcelVO.setUnitType(unitType);
                userExcelVO.setUnitName(unitDO.getUnitDetailName());
            } else {
                Long projectId = user.getProjectId();
                ProjectDO projectDO = projectMapper.selectDOById(projectId);
                userExcelVO.setUnitName(projectDO.getShigongUnit());
                userExcelVO.setUnitType("总包单位");
            }
            return userExcelVO;
        }).sorted(Comparator.comparing(ServiceUserExcelVO::getOrderEntranceTime).reversed()).collect(Collectors.toList());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("userExcelVOS", userExcelVOS);
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/manageUserExcelExcelTemplet.ftl").build(dataMap);
            AttachmentExportUtil.export(workbook, "云管理平台-建筑工地人员台账导出", response);
        } catch (IOException e) {
            log.error("云管理平台-建筑工地人员台账导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云管理平台-建筑工地人员台账导出失败");
        }
    }

    /**
     * 云监管平台-建筑工地人员台账导出
     *
     * @param request
     * @param response
     */
    @Override
    public void superviseUserExcelExport(ManageUserRegistrationRequest request, HttpServletResponse response) {
        if ("ZONGBAO_UNIT".equals(request.getUnitProperty())) {
            request.setZbUnitType(request.getUnitProperty());
            request.setUnitProperty(null);
        }
        List<ManageUserRegistrationDO> manageUserRegistrationDOList = manageUserRegistrationMapper.pageQueryByRequest(request);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(manageUserRegistrationDOList), "未查询到数据");
        List<DictItemVO> dictItemVOS = dictItemService.queryDictItemByDictCode("USER_JOB");
        List<DictItemVO> unitDicts = dictItemService.queryDictItemByDictCode("UNIT");
        List<DictItemVO> exitModes = dictItemService.queryDictItemByDictCode("OUT_TYPE");//离场方式
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
        List<ServiceUserExcelVO> userExcelVOS = manageUserRegistrationDOList.stream().map(user -> {
            UnitDO unitDO = unitMapper.selectDOById(user.getUnitId());
            String idCard = user.getIdCard();
            String province = user.getProvince();
            String city = user.getCity();
            String area = user.getArea();
            String resideAddress = user.getExitResideAddress();
            if (StringUtils.isEmpty(province)) {
                province = "";
            }
            if (StringUtils.isEmpty(city)) {
                city = "";
            }
            if (StringUtils.isEmpty(area)) {
                area = "";
            }
            if (StringUtils.isEmpty(resideAddress)) {
                resideAddress = "";
            }
            String address = province + city + area + resideAddress;
            ServiceUserExcelVO userExcelVO = ServiceUserExcelVO.builder().userName(user.getUserName()).userPhone(user.getUserPhone()).idCard(idCard).jobType(dictItemVOS.stream().filter(dictItemVO -> dictItemVO.getDictItemCode().equals(user.getJobType())).findFirst().orElse(new DictItemVO()).getDictItemName()).userAddress(user.getAddress()).inoculateNumber(!ObjectUtils.isEmpty(user.getInoculateNumber()) ? user.getInoculateNumber().toString() : null).entranceTime(!ObjectUtils.isEmpty(user.getEntranceTime()) ? formatter.format(user.getEntranceTime()) : null).commute(user.getCommute() == 0 ? "否" : "是").exitTime(!ObjectUtils.isEmpty(user.getExitTime()) ? formatter.format(user.getExitTime()) : null).exitMode(exitModes.stream().filter(dictItemVO -> dictItemVO.getDictItemCode().equals(user.getExitMode())).findFirst().orElse(new DictItemVO()).getDictItemName()).exitResideAddress(address).orderEntranceTime(user.getEntranceTime()).build();
            if (!ObjectUtils.isEmpty(unitDO)) {
                String unitType = unitDicts.stream().filter(dictItemVO -> dictItemVO.getDictItemCode().equals(unitDO.getUnitType())).findFirst().orElse(new DictItemVO()).getDictItemName();
                userExcelVO.setUnitType(unitType);
                userExcelVO.setUnitName(unitDO.getUnitDetailName());
            } else {
                Long projectId = user.getProjectId();
                ProjectDO projectDO = projectMapper.selectDOById(projectId);
                userExcelVO.setUnitName(projectDO.getShigongUnit());
                userExcelVO.setUnitType("总包单位");
            }
            return userExcelVO;
        }).sorted(Comparator.comparing(ServiceUserExcelVO::getOrderEntranceTime).reversed()).collect(Collectors.toList());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("userExcelVOS", userExcelVOS);
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/manageUserExcelExcelTemplet.ftl").build(dataMap);
            AttachmentExportUtil.export(workbook, "云监管平台-建筑工地人员台账导出", response);
        } catch (IOException e) {
            log.error("云监管平台-建筑工地人员台账导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云监管平台-建筑工地人员台账导出失败");
        }
    }

    @Override
    public void projectTempReportExcelExport(long tempTaskId, HttpServletResponse response) {
        // 查询导出数据
        ProjectReportExportVO projectReportExportVO = reportHelper.queryExportInfo(tempTaskId);
        // 组装导出数据（处理需要导出压缩包的图片文件）
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("columnSpan", CollectionUtils.isNotEmpty(projectReportExportVO.getColumns()) ? projectReportExportVO.getColumns().size() + 11 : 11);
        dataMap.put("tempReportHead", projectReportExportVO.getColumns());
        dataMap.put("tempReportList", projectReportExportVO.getValues());
        dataMap.put("project", projectReportExportVO.getProjectDOS());
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = null;
            if (CollectionUtils.isNotEmpty(projectReportExportVO.getColumns()) && CollectionUtils.isNotEmpty(projectReportExportVO.getValues())) {
                workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/projectTempReportExcelTemplat.ftl").build(dataMap);
                if (CollectionUtils.isEmpty(projectReportExportVO.getFiles())) {
                    AttachmentExportUtil.export(workbook, projectReportExportVO.getFileName(), response);
                    return;
                }
            }
            //zip文件名
            String fileName = projectReportExportVO.getFileName();
            ZipFileUtils.createZipFile(workbook, projectReportExportVO.getFileDirPath(), fileName, response);
        } catch (IOException e) {
            log.error("云监管平台-临时任务提报台账导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云监管平台-临时任务提报台账导出失败");
        }
    }

    @Override
    public void projectListTempReportExcelExport(ProjectReportStatisticsRequest request, HttpServletResponse response) {
        Pair<String, List<ProjectVO>> reportPair = tempHelper.queryExportData(request);
        AssertUtil.assertNotEmpty(reportPair.getRight(), "未查询到数据");
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("excelVOBuilders", SuperviseManageHotWorkExcelVOConvert.convert(reportPair.getRight()));
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/projectListTempReportExcelTemplat.ftl").build(dataMap);
            AttachmentExportUtil.export(workbook, reportPair.getLeft(), response);
        } catch (IOException e) {
            log.error("云监管-项目名单导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云监管-项目名单导出失败");
        }
    }

    @Override
    public void projectListFileExcelExport(ProjectFileTaskRequest request, HttpServletResponse response) {
        Pair<String, List<ProjectVO>> filePair = fileHelper.queryExportInfo(request);
        AssertUtil.assertNotEmpty(filePair.getRight(), "未查询到数据");
        List<SuperviseManageHotWorkExcelVO> excelVOBuilders = SuperviseManageHotWorkExcelVOConvert.convert(filePair.getRight());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("excelVOBuilders", excelVOBuilders);
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/projectListFileTaskExcelTemplat.ftl").build(dataMap);
            AttachmentExportUtil.export(workbook, filePair.getLeft(), response);
        } catch (IOException e) {
            log.error("云监管-文件接收项目名单导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云监管-文件接收项目名单导出失败");
        }
    }

    /**
     * 云管理-临时人员进出场纪录导出
     *
     * @param request
     * @param response
     */
    @Override
    public void manageTempUserExcelExport(ManageTempUserRegistrationRequest request, HttpServletResponse response) {
        List<ManageTempUserRegistrationDO> userRegistrationDOList = tempUserRegistrationMapper.selectByProject(request);
        List<ManageTempUserRegistrationVO> manageTempUserRegistrationVOS = ManageTempUserRegistrationConvert.buildManageTempUserRegistrationVoList(userRegistrationDOList);
        AssertUtil.assertNotEmpty(manageTempUserRegistrationVOS, "未查询到数据");
        List<ServiceTempUserExcelVO> tempUserExcelVOS = userRegistrationDOList.stream().map(tempUser -> {
            Date entranceTime = tempUser.getEntranceTime();
            Date approachTime = tempUser.getApproachTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
            String format = null;
            String a = null;
            if (!ObjectUtils.isEmpty(entranceTime)) {
                format = simpleDateFormat.format(entranceTime);
            }
            if (!ObjectUtils.isEmpty(approachTime)) {
                a = simpleDateFormat.format(approachTime);
            }
            QrCodeDO qrCodeDO = codeMapper.selectDOById(tempUser.getEntranceAddress());
            QrCodeDO qrCodeDO1 = codeMapper.selectDOById(tempUser.getApproachAddress());
            ServiceTempUserExcelVO build = ServiceTempUserExcelVO.builder().entranceTime(format).entranceAddress(!ObjectUtils.isEmpty(tempUser.getEntranceAddress()) ? (!ObjectUtils.isEmpty(qrCodeDO) ? qrCodeDO.getAddress() : null) : null).userName(tempUser.getUserName()).userPhone(tempUser.getUserPhone()).idNumber(tempUser.getIdNumber()).addressDetails(tempUser.getAddressDetails()).receiver(tempUser.getReceiver()).approachAddress(!ObjectUtils.isEmpty(tempUser.getApproachAddress()) ? (!ObjectUtils.isEmpty(qrCodeDO1) ? qrCodeDO1.getAddress() : null) : null).approachTime(a).sortEntranceTime(tempUser.getEntranceTime()).build();
            return build;
        }).sorted(Comparator.comparing(ServiceTempUserExcelVO::getSortEntranceTime).reversed()).collect(Collectors.toList());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("tempUserExcelVOS", tempUserExcelVOS);
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/manageTempUserExcelTemplet.ftl").build(dataMap);
            AttachmentExportUtil.export(workbook, "云管理平台-建筑工地人员台账导出", response);
        } catch (IOException e) {
            log.error("云管理平台-建筑工地人员台账导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云管理平台-建筑工地人员台账导出失败");
        }
    }

    /**
     * 云监管-动火作业导出
     *
     * @param request
     * @param response
     */
    @Override
    public void superviseHotWorkExcelExport(HotWorkRequest request, HttpServletResponse response) {
        Map<String, Date> time = hotWorkMapper.selectTimeScop(request);
        List<HotWorkDO> list = hotWorkMapper.pageDetailedList(request);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(list), "未查询到数据");
        List<DictItemVO> dictItemVOS = dictItemService.queryDictItemByDictCode("HOT_WORK_TYPE");
        List<DictItemVO> hotWorkLv = dictItemService.queryDictItemByDictCode("HOT_WORK_LV");
        List<HotWorkVO> hotWorkVOList = HotWorkConvert.buildHotWorkVoList(list);
        fillInfo(hotWorkVOList);
        String timeScop = "";
        if (!ObjectUtils.isEmpty(hotWorkVOList)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
            Date hotWorkDateStart = request.getHotWorkDateStart();
            Date hotWorkDateEnd = request.getHotWorkDateEnd();
            if (!ObjectUtils.isEmpty(hotWorkDateStart) && !ObjectUtils.isEmpty(hotWorkDateEnd)) {
                timeScop = dateFormat.format(hotWorkDateStart) + "~" + dateFormat.format(hotWorkDateEnd);
            } else {
                if (!ObjectUtils.isEmpty(time)) {
                    timeScop = dateFormat.format(time.get("minTime")) + "~" + dateFormat.format(time.get("maxTime"));
                }
            }
        }
        List<ServiceHotWorkExcelVO> hotWorkExcelVOS = hotWorkVOList.stream().map(hotWorkVO -> {
            Date hotWorkDateStart = hotWorkVO.getHotWorkDateStart();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
            String format = null;
            if (!ObjectUtils.isEmpty(hotWorkDateStart)) {
                format = formatter.format(hotWorkDateStart);
            }
            DictItemVO itemVO = hotWorkLv.stream().filter(a -> a.getDictItemCode().equals(hotWorkVO.getHotWorkLv())).findFirst().orElse(new DictItemVO());
            String dictItemName = dictItemVOS.stream().filter(dictItemVO -> dictItemVO.getDictItemCode().equals(hotWorkVO.getHotWorkType())).findFirst().orElse(new DictItemVO()).getDictItemName();
            return ServiceHotWorkExcelVO.builder().hotWorkCode(hotWorkVO.getHotWorkCode()).hotWorkPosition(hotWorkVO.getHotWorkPosition()).hotWorkType(dictItemName).hotWorkDate(format).unitName(hotWorkVO.getUnitDetailName()).hotWorkPersonName(hotWorkVO.getHotWorkPersonName()).hotWorkLookPersonOneName(hotWorkVO.getHotWorkLookPersonOneName()).hotWorkLookPersonTwoName(hotWorkVO.getHotWorkLookPersonTwoName()).safetyMeasure(hotWorkVO.getSafetyMeasure()).projectName(hotWorkVO.getProjectName()).projectNumber(hotWorkVO.getProjectNumber()).createTime(hotWorkVO.getCreateTime()).hotWorkLv(itemVO.getDictItemName()).build();
        }).sorted(Comparator.comparing(ServiceHotWorkExcelVO::getCreateTime).reversed()).collect(Collectors.toList());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("hotWorkList", hotWorkExcelVOS);
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/superviseHotWorkExcelTemplet.ftl").build(dataMap);
            List<File> files = hotWorkVOList.stream().map(a -> {
                String hotWorkCode = a.getHotWorkCode();
                String name = hotWorkCode + ".png";
                try {
                    if (!ObjectUtils.isEmpty(a.getHotWorkCard().trim())) {
                        File download = ZipFileUtils.download(name, a.getHotWorkCard());
                        return download;
                    }
                    return null;
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("云监管平台-动火证下载失败:{}", e.getMessage());
                    throw new BusinessException(ErrorCode.INTER_ERR, "云监管平台-动火证下载失败");
                }
            }).filter(a -> a != null).collect(Collectors.toList());
            HotWorkVO a = hotWorkVOList.get(0);
            String registrationNumber = a.getQualityRegistrationNumber();//质量监督注册号
            String projectName = a.getProjectName();
            String fileName = registrationNumber + "-" + projectName + "-" + timeScop + "动火作业导出";
            ZipFileUtils.downloadZip2(files, workbook, fileName, response);
        } catch (IOException e) {
            log.error("云监管-动火作业导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云监管-动火作业导出失败");
        }
    }

    /**
     * 云监管-动火作业管理列表导出
     *
     * @param request
     * @param response
     */
    @Override
    public void superviseManageHotWorkExcelExport(HotWorkRequest request, HttpServletResponse response) {
        List<Long> projectIds = axisMapper.selectDOByRequest(request);
        List<ProjectADO> hotWorkA = new ArrayList<>();
        if (!ObjectUtils.isEmpty(projectIds)) {
            request.setProjectIds(projectIds);
            hotWorkA = hotWorkMapper.selectDOListByIds(request);
        }
//        PageHelper.startPage(request.getPageNum(),request.getPageSize(),getOrderBy(pageable.getSort())).setReasonable(true);
        //查询时间范围内，上传了动火作业的项目及时间范围内曾处于在施状态的项目的动火作业数。
//        List<ProjectADO> hotWorkB = hotWorkMapper.selectDOListByNowRuning(request);
        List<ProjectADO> hotWorkADOS = hotWorkMapper.selectDOListByReq(request);
        if (CollectionUtils.isNotEmpty(hotWorkA)) {
            hotWorkADOS.addAll(hotWorkA);
        }
//        if (!ObjectUtils.isEmpty(hotWorkB)){
//            hotWorkADOS.addAll(hotWorkB);
//        }
        AssertUtil.assertNotEmpty(hotWorkADOS, "未查询到数据");
        List<StreetVO> streetVOS = streetService.queryStreetByAreaCode("110115");//地点
        List<DictItemVO> status = dictItemService.queryDictItemByDictCode("BUILD_TYPE");//施工状态
        List<DictItemVO> type = dictItemService.queryDictItemByDictCode("PROJECT_TYPE");//工程类型
        List<SuperviseManageHotWorkExcelVO> excelVOBuilders = hotWorkADOS.stream().map(project -> {
            Long id = project.getId();
            ProjectDO p = projectMapper.selectDOById(id);
            Date startDate = p.getStartDate();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String format = null;
            if (!ObjectUtils.isEmpty(startDate)) {
                format = simpleDateFormat.format(startDate);
            }
            SuperviseManageHotWorkExcelVO excelVO = SuperviseManageHotWorkExcelVO.builder().projectNumber(p.getProjectNumber()).qualityRegistrationNumber(p.getQualityRegistrationNumber()).projectName(p.getProjectName()).street(streetVOS.stream().filter(streetVO -> streetVO.getCode().equals(p.getStreetCode())).findFirst().orElse(new StreetVO()).getName()).address(p.getAddress()).engineeringType(type.stream().filter(itemVO -> itemVO.getDictItemCode().equals(p.getEngineeringType())).findFirst().orElse(new DictItemVO()).getDictItemName()).constructionStatus(status.stream().filter(itemVO -> itemVO.getDictItemCode().equals(p.getConstructionStatus())).findFirst().orElse(new DictItemVO()).getDictItemName()).startDate(format).floorArea(!ObjectUtils.isEmpty(p.getFloorArea()) ? p.getFloorArea().toPlainString() : null).engineeringCost(!ObjectUtils.isEmpty(p.getEngineeringCost()) ? p.getEngineeringCost().toPlainString() : null).shigongUnit(p.getShigongUnit()).shigongHeadName(p.getShigongHeadName()).shigongHeadPhone(p.getShigongHeadPhone()).shigongContactName(p.getShigongContactName()).shigongContactJob(p.getShigongContactJob()).shigongContactPhone(p.getShigongContactPhone()).jianliUnit(p.getJianliUnit()).jianliHeadName(p.getJianliHeadName()).jianliHeadPhone(p.getJianliHeadPhone()).jiansheUnit(p.getJiansheUnit()).jiansheHeadName(p.getJiansheHeadName()).jiansheHeadPhone(p.getJiansheHeadPhone()).hotWorkCount(!ObjectUtils.isEmpty(project.getHotWorkCount()) ? project.getHotWorkCount().toString() : "0").creatTime(project.getCreateTime()).build();
            return excelVO;
        }).sorted(Comparator.comparing(SuperviseManageHotWorkExcelVO::getCreatTime).reversed()).collect(Collectors.toList());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("excelVOBuilders", excelVOBuilders);
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/superviseManageHotWorkExcelTemplet.ftl").build(dataMap);
            AttachmentExportUtil.export(workbook, "云监管-动火作业管理列表导出", response);
        } catch (IOException e) {
            log.error("云监管-动火作业管理列表导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云监管-动火作业管理列表导出失败");
        }
    }

    /**
     * 云监管-临时人员进出项目纪录导出
     *
     * @param request
     * @param response
     */
    @Override
    public void supervisePersonTempUserExcelExport(ManageTempUserRegistrationRequest request, HttpServletResponse response) {
        Long jiansheUnitId = SessionContext.getJiansheUnitId();
        if (!ObjectUtils.isEmpty(jiansheUnitId)) {
            List<Long> projectIds = jiansheProjectMapper.selectAllProjectId(jiansheUnitId);
            request.setProjectIds(projectIds);
        }
        List<ManageTempUserRegistrationDO> userRegistrationDOList = tempUserRegistrationMapper.selectByPhoneOrName(request);
        List<ManageTempUserRegistrationVO> manageTempUserRegistrationVOS = ManageTempUserRegistrationConvert.buildManageTempUserRegistrationVoList(userRegistrationDOList);
        AssertUtil.assertNotEmpty(manageTempUserRegistrationVOS, "未查询到数据");
        fillProjectInfo(manageTempUserRegistrationVOS);
        List<ServiceTempUserExcelVO> userExcelVOS = manageTempUserRegistrationVOS.stream().map(user -> {
            Date entranceTime = user.getEntranceTime();
            Date approachTime = user.getApproachTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
            String format = null;
            String a = null;
            if (!ObjectUtils.isEmpty(entranceTime)) {
                format = simpleDateFormat.format(entranceTime);
            }
            if (!ObjectUtils.isEmpty(approachTime)) {
                a = simpleDateFormat.format(approachTime);
            }
            QrCodeDO qrCodeDO = codeMapper.selectDOById(user.getEntranceAddress());
            QrCodeDO qrCodeDO1 = codeMapper.selectDOById(user.getApproachAddress());
            ServiceTempUserExcelVO build = ServiceTempUserExcelVO.builder().projectNumber(user.getProjectNumber()).projectName(user.getProjectName()).street(user.getStreet()).engineeringType(user.getEngineeringType()).entranceTime(format).entranceAddress(!ObjectUtils.isEmpty(user.getEntranceAddress()) ? !ObjectUtils.isEmpty(qrCodeDO) ? qrCodeDO.getAddress() : null : null).receiver(user.getReceiver()).approachTime(a).approachAddress(!ObjectUtils.isEmpty(user.getApproachAddress()) ? !ObjectUtils.isEmpty(qrCodeDO1) ? qrCodeDO1.getAddress() : null : null).sortEntranceTime(user.getEntranceTime()).build();
            return build;
        }).sorted(Comparator.comparing(ServiceTempUserExcelVO::getSortEntranceTime).reversed()).collect(Collectors.toList());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("userExcelVOS", userExcelVOS);
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/superviseTempUserExcelTemplet.ftl").build(dataMap);
            AttachmentExportUtil.export(workbook, "云监管-临时人员进出项目纪录导出", response);
        } catch (IOException e) {
            log.error("云监管-临时人员进出项目纪录导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云监管-临时人员进出项目纪录导出失败");
        }
    }


    /**
     * 云监管-项目临时人员进出项目纪录导出-根据项目信息查询页面
     *
     * @param request
     * @param response
     */
    @Override
    public void superviseProjectTempUserExcelExport(ManageTempUserRegistrationRequest request, HttpServletResponse response) {
        List<ManageTempUserRegistrationDO> userRegistrationDOList = tempUserRegistrationMapper.selectByProject(request);
        List<ManageTempUserRegistrationVO> manageTempUserRegistrationVOS = ManageTempUserRegistrationConvert.buildManageTempUserRegistrationVoList(userRegistrationDOList);
        AssertUtil.assertNotEmpty(manageTempUserRegistrationVOS, "未查询到数据");
        fillProjectInfo(manageTempUserRegistrationVOS);
        List<ServiceTempUserExcelVO> tempUserExcelVOS = manageTempUserRegistrationVOS.stream().map(tempUser -> {
            Date entranceTime = tempUser.getEntranceTime();
            Date approachTime = tempUser.getApproachTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
            String format = null;
            String a = null;
            if (!ObjectUtils.isEmpty(entranceTime)) {
                format = simpleDateFormat.format(entranceTime);
            }
            if (!ObjectUtils.isEmpty(approachTime)) {
                a = simpleDateFormat.format(approachTime);
            }
            String province = tempUser.getProvince();
            String city = tempUser.getCity();
            String area = tempUser.getArea();
            String resideAddress = tempUser.getAddressDetails();
            if (org.apache.commons.lang3.StringUtils.isEmpty(province)) {
                province = "";
            }
            if (org.apache.commons.lang3.StringUtils.isEmpty(city)) {
                city = "";
            }
            if (org.apache.commons.lang3.StringUtils.isEmpty(area)) {
                area = "";
            }
            if (org.apache.commons.lang3.StringUtils.isEmpty(resideAddress)) {
                resideAddress = "";
            }
            String address = province + city + area + resideAddress;
            QrCodeDO qrCodeDO = codeMapper.selectDOById(tempUser.getEntranceAddress());
            QrCodeDO qrCodeDO1 = codeMapper.selectDOById(tempUser.getApproachAddress());
            ServiceTempUserExcelVO build = ServiceTempUserExcelVO.builder().entranceTime(format).entranceAddress(!ObjectUtils.isEmpty(tempUser.getEntranceAddress()) ? !ObjectUtils.isEmpty(qrCodeDO) ? qrCodeDO.getAddress() : null : null).userName(tempUser.getUserName()).userPhone(tempUser.getUserPhone()).idNumber(tempUser.getIdNumber()).addressDetails(address).receiver(tempUser.getReceiver()).approachAddress(!ObjectUtils.isEmpty(tempUser.getApproachAddress()) ? !ObjectUtils.isEmpty(qrCodeDO1) ? qrCodeDO1.getAddress() : null : null).approachTime(a).sortEntranceTime(tempUser.getEntranceTime()).build();
            return build;
        }).sorted(Comparator.comparing(ServiceTempUserExcelVO::getSortEntranceTime).reversed()).collect(Collectors.toList());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("tempUserExcelVOS", tempUserExcelVOS);
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/manageTempUserExcelTemplet.ftl").build(dataMap);
            AttachmentExportUtil.export(workbook, "云监管-临时人员进出项目纪录导出", response);
        } catch (IOException e) {
            log.error("云监管-临时人员进出项目纪录导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云监管-临时人员进出项目纪录导出失败");
        }
    }

    /**
     * 云监管-项目名单导出
     *
     * @param request
     * @param response
     */
    @Override
    public void superviseProjectExcelExport(ProjectRequest request, HttpServletResponse response) {
        List<ProjectDO> projectDOList = projectMapper.selectAllPassProject(request);
        List<ProjectVO> projectVOList = ProjectConvert.buildProjectVoList(projectDOList);
        AssertUtil.assertNotEmpty(projectVOList, "未查询到数据");
        List<StreetVO> streetVOS = streetService.queryStreetByAreaCode("110115");//地点
        List<DictItemVO> status = dictItemService.queryDictItemByDictCode("BUILD_TYPE");//施工状态
        List<DictItemVO> type = dictItemService.queryDictItemByDictCode("PROJECT_TYPE");//工程类型
        List<SuperviseManageHotWorkExcelVO> excelVOBuilders = projectVOList.stream().map(project -> {
            Long id = project.getId();
            ProjectDO p = projectMapper.selectDOById(id);
            Date startDate = p.getStartDate();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String format = null;
            if (!ObjectUtils.isEmpty(startDate)) {
                format = simpleDateFormat.format(startDate);
            }
            SuperviseManageHotWorkExcelVO excelVO = SuperviseManageHotWorkExcelVO.builder().projectNumber(p.getProjectNumber()).qualityRegistrationNumber(p.getQualityRegistrationNumber()).projectName(p.getProjectName()).street(streetVOS.stream().filter(streetVO -> streetVO.getCode().equals(p.getStreetCode())).findFirst().orElse(new StreetVO()).getName()).address(p.getAddress()).engineeringType(type.stream().filter(itemVO -> itemVO.getDictItemCode().equals(p.getEngineeringType())).findFirst().orElse(new DictItemVO()).getDictItemName()).constructionStatus(status.stream().filter(itemVO -> itemVO.getDictItemCode().equals(p.getConstructionStatus())).findFirst().orElse(new DictItemVO()).getDictItemName()).startDate(format).floorArea(!ObjectUtils.isEmpty(p.getFloorArea()) ? p.getFloorArea().toPlainString() : null).engineeringCost(!ObjectUtils.isEmpty(p.getEngineeringCost()) ? p.getEngineeringCost().toPlainString() : null).shigongUnit(p.getShigongUnit()).shigongHeadName(p.getShigongHeadName()).shigongHeadPhone(p.getShigongHeadPhone()).shigongContactName(p.getShigongContactName()).shigongContactJob(p.getShigongContactJob()).shigongContactPhone(p.getShigongContactPhone()).jianliUnit(p.getJianliUnit()).jianliHeadName(p.getJianliHeadName()).jianliHeadPhone(p.getJianliHeadPhone()).jiansheUnit(p.getJiansheUnit()).jiansheHeadName(p.getJiansheHeadName()).jiansheHeadPhone(p.getJiansheHeadPhone()).build();
            return excelVO;
        }).collect(Collectors.toList());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("excelVOBuilders", excelVOBuilders);
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/superviseProjectExcelTemplet.ftl").build(dataMap);
            AttachmentExportUtil.export(workbook, "云监管-项目名单导出", response);
        } catch (IOException e) {
            log.error("云监管-项目名单导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云监管-项目名单导出失败");
        }
    }

    private List<ProjectVO> filter(ProjectRequest request, List<ProjectVO> projectVOList) {
        projectVOList.forEach(item -> {
            Long id = item.getId();
            Date startTime = request.getStartTime();
            Date endTime = request.getEndTime();
            List<Long> in = manageUserRegistrationMapper.selectByTime(startTime,endTime,id);
            Integer out = manageUserRegistrationMapper.selectOutByTime(startTime,endTime,id);
            Date lastUpdateTime = manageUserRegistrationMapper.selectLastUpdateTime(id);
            //进场人次
            item.setInCount(in.size());
            //离场人次
            item.setOutCount(out);
            //最后更新时间
            item.setLastUpdateTime(lastUpdateTime);
        });

        Boolean excludeIn = request.getExcludeIn();
        Boolean excludeOut = request.getExcludeOut();
        if (ObjectUtils.isEmpty(excludeIn)) {
            excludeIn = false;
        }
        if (ObjectUtils.isEmpty(excludeOut)) {
            excludeOut = false;
        }
        if (excludeIn) {
            if (excludeOut) {
                return projectVOList.stream().filter(item -> item.getPersonCount() > 0 && (item.getInCount() > 0 || item.getOutCount() > 0))
                        .sorted(Comparator.comparing(ProjectVO::getCreateTime).reversed())
                        .collect(Collectors.toList());
            } else {
                return projectVOList.stream().filter(item -> item.getPersonCount() > 0)
                        .sorted(Comparator.comparing(ProjectVO::getCreateTime).reversed())
                        .collect(Collectors.toList());
            }
        } else {
            if (excludeOut) {
                return projectVOList.stream().filter(item -> item.getInCount() > 0 || item.getOutCount() > 0)
                        .sorted(Comparator.comparing(ProjectVO::getCreateTime).reversed())
                        .collect(Collectors.toList());
            } else {
                return projectVOList.stream().sorted(Comparator.comparing(ProjectVO::getCreateTime).reversed())
                        .collect(Collectors.toList());
            }
        }
    }

    /**
     * 云监管-项目人员统计导出
     *
     * @param request
     * @param response
     */
    @Override
    public void supervisePersonExcelExport(ProjectRequest request, HttpServletResponse response) {
        List<ProjectDO> projectDOList = projectMapper.supervisePageQueryRecords(request);
        List<ProjectVO> projectVOList = filter(request, ProjectConvert.buildProjectVoList(projectDOList));
        AssertUtil.assertNotEmpty(projectVOList, "未查询到数据");
        List<StreetVO> streetVOS = streetService.queryStreetByAreaCode("110115");//地点
        List<DictItemVO> status = dictItemService.queryDictItemByDictCode("BUILD_TYPE");//施工状态
        List<DictItemVO> type = dictItemService.queryDictItemByDictCode("PROJECT_TYPE");//工程类型
        List<SuperviseManageHotWorkExcelVO> excelVOBuilders = projectVOList.stream().map(pro -> {
            Long projectId = pro.getId();
            ProjectDO p = projectMapper.selectDOById(projectId);
            Date startDate = p.getStartDate();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            SimpleDateFormat lastUpdateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String format = null;
            if (!ObjectUtils.isEmpty(startDate)) {
                format = simpleDateFormat.format(startDate);
            }
            String format1 = null;
            Date lastUpdateTime = pro.getLastUpdateTime();
            if (lastUpdateTime != null) {
                format1 = lastUpdateTimeFormat.format(lastUpdateTime);
            }
            SuperviseManageHotWorkExcelVO excelVO = SuperviseManageHotWorkExcelVO.builder().
                    projectNumber(p.getProjectNumber())
                    .qualityRegistrationNumber(p.getQualityRegistrationNumber())
                    .projectName(p.getProjectName()).street(streetVOS.stream().filter(streetVO -> streetVO.getCode().equals(p.getStreetCode())).findFirst().orElse(new StreetVO()).getName()).address(p.getAddress()).engineeringType(type.stream().filter(itemVO -> itemVO.getDictItemCode().equals(p.getEngineeringType())).findFirst().orElse(new DictItemVO()).getDictItemName()).constructionStatus(status.stream().filter(itemVO -> itemVO.getDictItemCode().equals(p.getConstructionStatus())).findFirst().orElse(new DictItemVO()).getDictItemName()).startDate(format).floorArea(!ObjectUtils.isEmpty(p.getFloorArea()) ? p.getFloorArea().toPlainString() : null).engineeringCost(!ObjectUtils.isEmpty(p.getEngineeringCost()) ? p.getEngineeringCost().toPlainString() : null).shigongUnit(p.getShigongUnit()).shigongHeadName(p.getShigongHeadName()).shigongHeadPhone(p.getShigongHeadPhone()).shigongContactName(p.getShigongContactName()).shigongContactJob(p.getShigongContactJob()).shigongContactPhone(p.getShigongContactPhone()).jianliUnit(p.getJianliUnit()).jianliHeadName(p.getJianliHeadName()).jianliHeadPhone(p.getJianliHeadPhone()).jiansheUnit(p.getJiansheUnit()).jiansheHeadName(p.getJiansheHeadName()).jiansheHeadPhone(p.getJiansheHeadPhone()).personCount(!ObjectUtils.isEmpty(pro.getPersonCount()) ? pro.getPersonCount().toString() : "0").creatTime(p.getCreateTime()).inCount(pro.getInCount().toString()).outCount(pro.getOutCount().toString()).lastUpdateTime(format1).build();
            return excelVO;
        }).sorted(Comparator.comparing(SuperviseManageHotWorkExcelVO::getCreatTime).reversed()).collect(Collectors.toList());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("excelVOBuilders", excelVOBuilders);
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Workbook workbook = excelBuilder.workbookType(WorkbookType.XLSX).classpathTemplate("/template/supervisePersonExcelTemplet.ftl").build(dataMap);
            AttachmentExportUtil.export(workbook, "云监管-项目人员统计导出", response);
        } catch (IOException e) {
            log.error("云监管-项目人员统计导出失败:{}", e.getMessage());
            throw new BusinessException(ErrorCode.INTER_ERR, "云监管-项目人员统计导出失败");
        }
    }

    private void fillProjectInfo(List<ManageTempUserRegistrationVO> manageTempUserRegistrationVOS) {
        List<DictItemVO> type = dictItemService.queryDictItemByDictCode("PROJECT_TYPE");//工程类型
        List<StreetVO> streetVOS = streetService.queryStreetByAreaCode("110115");//地点
        for (ManageTempUserRegistrationVO vo : manageTempUserRegistrationVOS) {
            //项目信息
            ProjectDO project = projectMapper.selectDOById(vo.getProjectId());
            if (project != null) {
                vo.setProjectName(project.getProjectName());
                vo.setProjectNumber(project.getProjectNumber());
                vo.setQualityRegistrationNumber(project.getQualityRegistrationNumber());
                vo.setEngineeringType(type.stream().filter(itemVO -> itemVO.getDictItemCode().equals(project.getEngineeringType())).findFirst().orElse(new DictItemVO()).getDictItemName());
                vo.setStreet(streetVOS.stream().filter(streetVO -> streetVO.getCode().equals(project.getStreetCode())).findFirst().orElse(new StreetVO()).getName());
                vo.setShigongUnit(project.getShigongUnit());
            }
        }
    }

    private void fillInfo(List<HotWorkVO> hotWorkList) {
        for (HotWorkVO vo : hotWorkList) {
            //项目信息
            ProjectDO project = projectMapper.selectDOById(vo.getProjectId());
            if (project != null) {
                vo.setProjectName(project.getProjectName());
                vo.setProjectNumber(project.getProjectNumber());
                vo.setQualityRegistrationNumber(project.getQualityRegistrationNumber());
            }
            //分包单位信息
            UnitDO unitDO = unitMapper.selectDOById(vo.getUnitId());
            if (!ObjectUtils.isEmpty(unitDO)) {
                vo.setUnitName(unitDO.getUnitName());
                vo.setUnitDetailName(unitDO.getUnitDetailName());
            }
            //动火人信息
            ManageUserRegistrationDO registrationDO = manageUserRegistrationMapper.selectById(vo.getHotWorkPerson());
            if (!ObjectUtils.isEmpty(registrationDO)) {
                vo.setHotWorkPersonName(registrationDO.getUserName());
                vo.setHotWorkPersonPhoto(registrationDO.getExitFacePhoto());
            }
            //看火人1
            ManageUserRegistrationDO registrationDOOne = manageUserRegistrationMapper.selectById(vo.getHotWorkLookPersonOne());
            if (!ObjectUtils.isEmpty(registrationDOOne)) {
                vo.setHotWorkLookPersonOneName(registrationDOOne.getUserName());
                vo.setHotWorkLookPersonOnePhoto(registrationDOOne.getExitFacePhoto());
            }
            //看火人2
            Long hotWorkLookPersonTwo = vo.getHotWorkLookPersonTwo();
            if (!ObjectUtils.isEmpty(hotWorkLookPersonTwo)) {
                ManageUserRegistrationDO registrationDOTwo = manageUserRegistrationMapper.selectById(vo.getHotWorkLookPersonTwo());
                if (!ObjectUtils.isEmpty(registrationDOTwo)) {
                    vo.setHotWorkLookPersonTwoName(registrationDOTwo.getUserName());
                    vo.setHotWorkLookPersonTwoPhoto(registrationDOTwo.getExitFacePhoto());
                }
            }

        }
    }
}
